package com.zzyl.oss.client;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.zzyl.oss.properties.AliOssConfigProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Slf4j
@Component
public class OSSAliyunFileStorageService {

    private OSS ossClient;

    private AliOssConfigProperties aliOssConfigProperties;

    @Autowired
    public OSSAliyunFileStorageService(OSS ossClient, AliOssConfigProperties aliOssConfigProperties) {
        this.ossClient = ossClient;
        this.aliOssConfigProperties = aliOssConfigProperties;
    }

    /**
     * 上传文件
     * @param file
     * @return
     */
    public String upload(MultipartFile file) {
        // 检查OSS客户端是否初始化
        if (ossClient == null) {
            throw new RuntimeException("OSS客户端未初始化，请检查OSS配置是否正确");
        }
        
        if (aliOssConfigProperties.getBucketName() == null || aliOssConfigProperties.getBucketName().isEmpty()) {
            throw new RuntimeException("OSS Bucket名称未配置，请检查配置文件");
        }

        try {
            //获取上传文件的输入流
            InputStream inputStream = file.getInputStream();

            //获取原始文件名
            String originalFileName = file.getOriginalFilename();
            if (originalFileName == null) {
                originalFileName = "unknown_file";
            }
            
            //获取文件后缀名
            String extension = "";
            int dotIndex = originalFileName.lastIndexOf(".");
            if (dotIndex != -1 && dotIndex < originalFileName.length() - 1) {
                extension = originalFileName.substring(dotIndex);
            }

            //使用UUID生成新的文件名
            String newFileName = UUID.randomUUID().toString() + extension;

            //拼接文件夹
            String folder = "images/";
            //拼接文件名
            String fileName = folder + newFileName;

            //调用阿里云OSS上传文件
            PutObjectRequest putObjectRequest = new PutObjectRequest(aliOssConfigProperties.getBucketName(), fileName, inputStream);
            PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);

            //构建文件访问路径
            String filePath = "https://" + aliOssConfigProperties.getBucketName() + "." + aliOssConfigProperties.getEndpoint() + "/" + fileName;

            return filePath;
        } catch (OSSException oe) {
            log.error("OSS异常，错误码：{}，错误信息：{}", oe.getErrorCode(), oe.getMessage());
            throw new RuntimeException("文件上传失败，OSS异常");
        } catch (ClientException ce) {
            log.error("客户端异常，错误信息：{}", ce.getMessage());
            throw new RuntimeException("文件上传失败，客户端异常");
        } catch (IOException e) {
            log.error("IO异常，错误信息：{}", e.getMessage());
            throw new RuntimeException("文件上传失败，IO异常");
        }
    }
}